/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.web.servlet;

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * 接口，用于需要获取 {@link DispatcherServletAutoConfiguration#DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME
 * 默认} {@link DispatcherServlet} 路径信息的自动配置场景。
 *
 * @author Madhura Bhave
 * @author Stephane Nicoll
 * @since 2.0.4
 */
@FunctionalInterface
public interface DispatcherServletPath {

	/**
	 * 返回 DispatcherServlet 配置的路径。
	 * @return 配置的路径
	 */
	String getPath();

	/**
	 * 返回相对于 DispatcherServlet 路径的给定路径的相对形式。
	 * @param path 需要转换为相对路径的路径
	 * @return 相对路径
	 */
	default String getRelativePath(String path) {
		String prefix = getPrefix();
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		return prefix + path;
	}

	/**
	 * 返回一个清理后的路径版本，可用作 URL 的前缀。结果路径不会以斜杠结尾。
	 * @return 路径前缀
	 * @see #getRelativePath(String)
	 */
	default String getPrefix() {
		String result = getPath();
		int index = result.indexOf('*');
		if (index != -1) {
			result = result.substring(0, index);
		}
		if (result.endsWith("/")) {
			result = result.substring(0, result.length() - 1);
		}
		return result;
	}

	/**
	 * 返回一个可用于 {@link ServletRegistrationBean} 映射 DispatcherServlet 的 URL 映射模式。
	 * @return 作为 Servlet URL 映射的路径
	 */
	default String getServletUrlMapping() {
		if (getPath().equals("") || getPath().equals("/")) {
			return "/";
		}
		if (getPath().contains("*")) {
			return getPath();
		}
		if (getPath().endsWith("/")) {
			return getPath() + "*";
		}
		return getPath() + "/*";
	}

}
